import React, { Component } from 'react';
import './scss/ReceiveNewsList.scss';
// import Header from '../../common/compont/Header';
import Header from './header/Header';
// import Navigation from './Navigation';
import Footer from '../../common/compont/Footer';
import { Pagination, message } from 'antd';
import { getData, getQueryVariable, getRealPath, axiosMethod } from '../../common/js/fetch';
import { LgButton, LgPaginationA, LgSearch, LgSelect } from 'lancoo-web-ui';
import { SKIN_BG_COLOR } from '../../hooks/useGetThem'
class ReceiveNewsList extends Component {
    constructor(props) {
        super(props);
        // console.log(props,'props');
        this.state = {
            NewsTypeList: [],
            NewsTypeListId: [],
            NewsList: [],
            chooseIdx: '',
            PageIndex: 1,
            openAddEvent: false,
            headerName: '新闻公告',
            total: 0,
            pageSize: 8,
            systemInfo: JSON.parse(sessionStorage.getItem('systemInfo')),
            skin: 's2',
            selectValue: '全部类型',
            selectValueB: '全部状态',
            datalistB: [
                {
                    text: "全部状态",
                    status: ''
                },
                {
                    text: "已发布",
                    status: '1'
                },
                {
                    text: "未发布",
                    status: '0'
                },
            ],
            chooseOne: false,
            releaseStatus: '',
            typeId: '',
            sortType: 0,
            user: '',
        };
        this.onChangePage = this.onChangePage.bind(this);

        this.handleQueryChange = this.handleQueryChange.bind(this);
    }

    componentDidMount() {
        document.title = '部门资讯'
        axiosMethod(sessionStorage.getItem('baseUrl') + 'openapi/v1/system/facade/getSkin', {
            appid: '211',
            token: getQueryVariable('lg_tk'),
        }).then(res => res.json()).then(res => {
            console.log(res)
            if (res.StatusCode == '200') {
                // dispatch({
                //   type: 'SET_SKIN',
                //   data: `s${res.Data.skin}`
                // })
                sessionStorage.setItem('skin', `s${res.Data.skin}`);
                this.setState({
                    skin: `s${res.Data.skin}`
                })
            }
        })
        getData('api/news/type/send/type/list', {
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
        }).then(res => {
            return res.json()
        }).then(json => {
            console.log(json);
            if (json.code == 200 && json.data) {
                console.log(json.data);
                let typeList = []
                if(json.data.length > 0) {
                    json.data.forEach(i => {
                        typeList.push({
                            newsTypeId: i.newsTypeId, text: i.newTypeName, schoolId: sessionStorage.getItem('schoolId')
                        })
                    })
                }
                typeList.unshift({ newsTypeId: "", text: "全部类型", schoolId: sessionStorage.getItem('schoolId') });
                this.setState({
                    NewsTypeList: typeList,
                }, () => {
                    this.getNewsList(0);
                })

                // let data = json.data;
                // data.forEach(item => {
                //     item.text = item.newTypeName;
                // });
                // if (systemInfo.beEdu == '1') {
                //     data.unshift({ newsTypeId: '', text: '全部类型' }, { newsTypeId: '0', text: '校园资讯' });
                // } else {
                //     data.unshift({ newsTypeId: '', text: '全部类型' });
                // }
                // console.log(data)
                // this.setState({
                //     NewsTypeList: data,
                // })

            } else {
                message.error(json.Msg);
                return
                // alert(json.Msg);
            }
        })
    }
    getNewsList(idx) {
        getData('api/news/list/page', {
            // NewsTypeName: idx === 0 ? '' : encodeURIComponent(this.state.NewsTypeList[idx]),
            pageNum: this.state.PageIndex,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            userId: this.state.chooseOne ? this.state.user : '',
            userType: sessionStorage.getItem('UserType'),
            pageSize: 8,
            releaseStatus: 1,
            typeId: this.state.typeId,
        }).then(res => {
            return res.json()
        }).then(json => {
            // console.log(json);
            if (json.code == 200) {
                this.setState({
                    NewsList: json.data,
                    total: json.total,
                }, () => {
                    if (this.state.total > 8) {
                        // document.getElementsByClassName('ant-pagination-options-quick-jumper')[0].childNodes[0].nodeValue = '到'
                    }
                })

            } else {
                // const history = createHashHistory();
                // history.push('/404');
                return
                // alert(json.Msg);
            }
        })
    }
    changeChooseLi(idx) {
        if (idx !== this.state.chooseIdx) {
            this.setState({
                chooseIdx: idx,
                PageIndex: 1,
            }, () => {
                this.getNewsList(idx);
            })

        }
    }
    addEvent(elm, event, handler) {
        if (window.attachEvent) {
            elm.attachEvent("on" + event, handler);
        } else if (window.addEventListener) {
            elm.addEventListener(event, handler);
        } else {
            elm['on' + event] = handler;
        }
    }
    gotContent(item) {
        let $this = this;
        console.log('跳转的详情！')
        if (!this.state.openAddEvent) {
            this.setState({
                openAddEvent: true
            })
            this.addEvent(window, 'message', function (e) {
                // console.log(e.data == 11);
                try {
                    if (e.data === 11) {
                        $this.getNewsList($this.state.chooseIdx);
                    }
                } catch (ex) {
                }
            }, false);
        }
        let token = getQueryVariable('lg_tk') || sessionStorage.getItem('token')

        let url = window.location.href.split('#/')[0] + '#/RecNewsContent?lg_tk=' + getQueryVariable('lg_tk') + '&lg_ic=' + getQueryVariable('lg_ic') + '&newsId=' + item.newsId;
        // url = getRealPath() + '#/RecNewsContent?lg_tk=' + token + '&lg_ic=' + getQueryVariable('lg_ic') + '&newsId=' + item.newsId
        console.log(url)
        console.log("需要跳转的链接：", item.URL + sessionStorage.getItem('token'))
        console.log("后台返回的token信息：", item.URL)
        window.open(url, '_blank');
    }
    onChangePage(page) {
        this.setState({
            PageIndex: page
        }, () => {
            this.getNewsList(this.state.chooseIdx);
        })
    }
    handleKeyPress(event) {
        if (event.key === 'Enter') {
            this.handleSearch();
        }
    }

    handleQueryChange(event) {
        this.setState({
            Keyword: event.target.value
        });
    }
    //页码选择
    changePageA = (page) => {
        console.log('page', page);
        this.setState({
            PageIndex: page
        }, () => {
            this.getNewsList();
        })

    }
    SelectOptionA = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValue: item.text,
            typeId: item.newsTypeId,
            // chooseOne: false,
            PageIndex: 1,
        }, () => {
            this.getNewsList()
        })
    }
    SelectOptionB = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValueB: item.text,
            releaseStatus: item.status,
            // chooseOne: false,
            PageIndex: 1,
        }, () => {
            this.getNewsList()
        })
    }
    reloadType = () => {
        this.setState({
            selectValue: '全部类型',
            typeId: '',
            selectValueB: '全部状态',
            releaseStatus: '',
            // chooseOne: false,
            PageIndex: 1,
        })
    }

    ChooseOne() {
        if (this.state.chooseOne == true) {
            this.setState({
                chooseOne: !this.state.chooseOne,
                PageIndex: 1,
                Keyword: '',
                user: ''
            }, () => {
                this.getNewsList(this.state.user);
                this.setState({
                    user: ''
                })
            })
        } else {
            this.setState({
                chooseOne: !this.state.chooseOne,
                PageIndex: 1,
                Keyword: '',
                user: sessionStorage.getItem('UserID')
            }, () => {
                this.getNewsList(this.state.user);
            })
        }
    }
    getChildrenMsg(keyword) {
        let {
            typeId,
            releaseStatus,
            user,
            chooseOne,
            sortType
        } = this.state
        getData('api/news/list/page', {
            pageNum: 1,
            pageSize: 8,
            keyWord: encodeURIComponent(keyword),
            userId: chooseOne ? user : '',
            typeId: typeId,
            releaseStatus: 1,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            sortType: sortType,
            userType: sessionStorage.getItem('UserType'),
        }).then((res) => {
            return res.json()
        }).then((json) => {
            // console.log(json);
            // hide();
            if (json.code == 200 && json.data) {
                this.setState({
                    Keyword: keyword,
                    Newstype: '全部类别',
                    NewsList: json.data,
                    total: json.total,
                    // Newstype: '全部类别',
                    // PageIndex: page,
                    // chooseOne: false,
                })
            } else {
                if (json.StatusCode == 403) {
                    const history = createHashHistory();
                    history.push('/Error');
                    return
                }
                message.error(json.msg, 3);
            }
        })
    }
    render() {
        let {
            total,
            PageIndex,
            pageSize,
            systemInfo,
            selectValue,
            datalistB,
            selectValueB,
        } = this.state
        return (
            <div>
                <Header headerStyle={3} headerName={'部门资讯'}></Header>
                <div className='ReceiveNews-all' style={{
                    backgroundColor: SKIN_BG_COLOR[this.state.skin]
                }}>
                    <div className='ReceiveNews-main'>
                        {/* <div className='ReceiveNews-typelist'><span>类型:</span><ul>
                            {this.state.NewsTypeList.length > 0 && this.state.NewsTypeList.map((item, idx) => {
                                return <li onClick={() => { this.changeChooseLi(item.newsTypeId) }} key={idx} className={this.state.chooseIdx === item.newsTypeId ? 'chooseLi' : ''}> {item.newTypeName} <b></b></li>
                            })}</ul></div> */}
                        <div className='newsList-choose-user' >
                            {
                                this.state.NewsTypeList.length > 0 && <div className='div-select'>
                                    <LgSelect className='select-type'
                                        datalist={this.state.NewsTypeList} SelectOption={this.SelectOptionA}
                                        placeholder='请选择' width={150}
                                        value={selectValue}
                                    ></LgSelect>
                                    <div>
                            <i className={this.state.chooseOne ? 'chooseOne' : 'chooseMore'} onClick={() => { this.ChooseOne() }}></i><span className='chooseOne-span' onClick={() => { this.ChooseOne() }}>只看自己发布的</span>

                                    </div>
                                </div >
                            }
                            {/* <div className='div-select div-select-status'>
                                <LgSelect className='select-type'
                                    datalist={datalistB} SelectOption={this.SelectOptionB}
                                    placeholder='请选择' width={150}
                                    value={selectValueB}
                                ></LgSelect>
                            </div > */}
                            <div style={{ display: 'inline-block', paddingRight: '20px' }} >
                                <LgSearch className='search-news' onSearch={(value) => this.getChildrenMsg(value)} onClear={() => this.getChildrenMsg('')}
                                    value={this.state.Keyword} input={{ disabled: false, placeholder: "搜索新闻资讯标题/发布者姓名...", onChange: (e) => this.handleQueryChange(e), onKeyPress: (e) => this.handleKeyPress(e) }} ></LgSearch>
                                {/* <LgButton className='News-create-button' backgroundType='opacification' showIcon icon={<LgButton.icon.Add></LgButton.icon.Add>} type='success' onClick={() => { this.createNews() }}>
                                创建新闻资讯</LgButton> */}
                                {/* <LgButton style={{ marginLeft: '12px' }} backgroundType='opacification' showIcon icon={<LgButton.icon.Add></LgButton.icon.Add>} gradient type='success' onClick={() => { this.createNews() }}>创建新闻资讯</LgButton> */}
                            </div>
                        </div>
                        <div>
                            {this.state.NewsList.length > 0 ? <ul className="ReceiveNewsList-ul">
                                {this.state.NewsList.length > 0 && this.state.NewsList.map((item, idx) => {
                                    let words = item.newsContent.replace(/<[^<>]+>/g, "").replace(/&nbsp;/gi, "");
                                    if (item.beEduPush == '1' && item.newsCoverPath != '') {
                                        if (!item.newsCoverPath.toLowerCase().includes('https://')) {
                                            item.newsCoverPath = systemInfo.governmentWebUrl + '/' + item.newsCoverPath
                                        }
                                        // console.log(item.newsCoverPath, 'item.newsCoverPath');
                                    }
                                    // console.log(words);
                                    return <li key={idx} onClick={() => { this.gotContent(item) }}>
                                        <i className='news-i' style={item.newsCoverPath?.length > 0 ? { backgroundImage: 'url(' + item.newsCoverPath + ')' } : {}} ></i>
                                        {/* <b className='none-i-tips'>图片丢失</b> */}
                                        <span className='news-span'> <b title={item.newsTitle}> {item.newsTitle}</b>  <b className='news-type'>{item.newsTypeName}</b>  </span>
                                        <b className='news-contant' title={words}> {words.length > 90 ? words.slice(0, 88) + '...' : words} </b>
                                        <span className='news-span2'><b className='news-time'>发布时间: {item.releaseTime}     </b> <b> 阅读次数: {item.readCount ? item.readCount : 0}次 </b> <b> 发布者: {item.userName} </b></span>
                                    </li>
                                })}
                            </ul> : <div className='newsList-empty'> <i></i><p>暂无新闻资讯~</p></div>}
                        </div>
                        {
                            total > 8 ?
                                <div className="news-Pagination lg-skin-s2">
                                    <LgPaginationA
                                        total={Math.ceil(total / pageSize)}
                                        size="normal"
                                        currentPage={PageIndex}
                                        onChangePage={this.changePageA}
                                    ></LgPaginationA>
                                    {/* <Pagination className="notice-ant-Pagination"  showQuickJumper={{goButton:<LgButton size='small' style={{height:'32px', marginLeft:'10px',color:' rgba(0, 0, 0, 0.65)'}}>GO</LgButton>}}  hideOnSinglePage={true} pageSize={8} showTotal={(total, pageSize) => `共 ${Math.ceil(total / 10)} 页`} defaultCurrent={1} current={this.state.PageIndex} total={this.state.total} onChange={this.onChangePage} /> */}
                                </div>
                                : ''
                        }
                    </div>
                </div>
                {/* <Footer></Footer> */}

            </div >
        )

    }

}

export default ReceiveNewsList;